cmake_minimum_required(VERSION 3.0.0)

include_guard(GLOBAL)

include(${CMAKE_SOURCE_DIR}/cmake/component.cmake)

function(py_library)
  if(NOT NS)
    message(FATAL_ERROR "Undefined NS!")
  endif()
  if(${ARGC} EQUAL 1)
    set(REPO_SITE_PKGS_DIR ${ARGV0})
  else()
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/site-packages)
      set(REPO_SITE_PKGS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/site-packages)
      configure_file(${CMAKE_SOURCE_DIR}/cmake/in/component.py.in ${REPO_SITE_PKGS_DIR}/component.py @ONLY)
    else()
      unset(REPO_SITE_PKGS_DIR)
    endif()
  endif()

  if(REPO_SITE_PKGS_DIR)
    set(SITE_PKGS_DIR ${CMAKE_BINARY_DIR}/site-packages)
    file(RELATIVE_PATH PROJ_REL_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR})
    set(SITE_PKG_SRC_DIR ${SITE_PKGS_DIR}/${PROJ_REL_PATH})
    if (${CMAKE_VERSION} VERSION_LESS "3.20.0")
      get_filename_component(SITE_PKG_PARENT_DIR ${SITE_PKG_SRC_DIR} DIRECTORY)
    else()
      cmake_path(GET SITE_PKG_SRC_DIR PARENT_PATH SITE_PKG_PARENT_DIR)
    endif()
    file(MAKE_DIRECTORY ${SITE_PKG_PARENT_DIR})
    file(CREATE_LINK ${REPO_SITE_PKGS_DIR}/ ${SITE_PKG_SRC_DIR} SYMBOLIC)
  else()
    message(FATAL_ERROR "site-packages missing for ${NS}__${PROJECT_NAME}!")
  endif()
endfunction()
